# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required
#import gdata.contacts.data
#import gdata.contacts.service
import datetime
import lunar
import oauth
import logging

import httplib
import urllib
from django.utils import simplejson as json

icalTemplate0 = u"""BEGIN:VCALENDAR
PRODID:-//bsdjy.com//生日//CN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-PUBLISHED-TTL:PT1H
X-WR-TIMEZONE;VALUE=TEXT:Asia/Shanghai
X-WR-CALNAME;VALUE=TEXT:生日
X-WR-CALDESC;VALUE=TEXT:农历生日"""

icalTemplate1 = u"""
BEGIN:VEVENT
DTSTART;VALUE=DATE:%(dtstart)s
DTEND;VALUE=DATE:%(dtend)s
DTSTAMP:%(dtnow)s
UID:-%(index)s@http://contactsbirthday.appspot.com
CLASS:PUBLIC
CREATED:%(dtnow)s
DESCRIPTION;VALUE=TEXT:今天是%(name)s%(type)s的生日
LAST-MODIFIED:%(dtnow)s
LOCATION:
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY;VALUE=TEXT:%(name)s的生日
TRANSP:OPAQUE
END:VEVENT"""

icalTemplate2 = """
END:VCALENDAR"""


class ICALPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        
        credential = None
        email = self.request.get('email')
        if email:
            credentials = oauth.Credentials.all()
            for c in credentials:
                if c.user.email() == email:
                    credential = c
                    break
        else:
            return
        
        if credential.expire_date < datetime.datetime.now():
            logging.debug('update credential')
            param = urllib.urlencode({
                'email': email
            })
            self.redirect('/oauthupdate?'+param)
            return
        
        birthdays = []
        
        self.auth_token = credential.access_token
        self.response.out.write(icalTemplate0)
        
        logging.debug('token %s', credential.access_token)
        
        
        headers = {
            'Authorization': u'OAUTH'+credential.access_token,
            'GData-Version': '3.0'
        }

        param = urllib.urlencode({
            'alt': 'json',
            'oauth_token': credential.access_token,
            'max-results': 9999
        })
        url = u'/m8/feeds/contacts/default/full?'+param
        conn = httplib.HTTPSConnection('www.google.com')
        conn.request('GET', url, body='', headers=headers)
        r1 = conn.getresponse()
        
        
        if r1.status == 200:
            d = json.loads(r1.read())
            for entry in d['feed'].get('entry', []):
                if 'gd$name' not in entry:
                    continue
                name = entry['gd$name']['gd$fullName']['$t']
                solar_birthday = ''
                lunar_birthday = ''
                if 'gContact$birthday' in entry:
                    solar_birthday = entry['gContact$birthday']['when']
                if 'gContact$event' in entry:
                    for event in entry['gContact$event']:
                        if event['label'] == u'农历生日':
                            lunar_birthday = event['gd$when']['startTime']
                            break
                
                if solar_birthday!='' and solar_birthday!=lunar_birthday:
                    birthdays.append((name, solar_birthday, 1))
                if lunar_birthday!='':      
                    birthdays.append((name, lunar_birthday, -1))
        else:
            error_msg = 'Invalid response %s.' % r1.status
            self.response.out.write(error_msg)
        
   
    
       
        year_number = datetime.datetime.today().year
        index = 0
        
        for year in range(year_number-1, year_number+2):
            for birthday in birthdays:
                name, t = birthday[0], ''            
                #date tuple, start date, end date 
                d1, d2, d3 = birthday[1].split('-'), None, None 
                    
                if birthday[-1] == -1:
                    t = u'阴历'
                    d2list = lunar.get_solar_date(year, int(d1[1]), int(d1[2]))
                    for d2 in d2list:                    
                        d3 = d2 + datetime.timedelta(days=1)
                        index = index+1
                        self.response.out.write(icalTemplate1 % {'name': name, 
                                                        'dtstart': d2.strftime('%Y%m%d'),
                                                        'dtend': d3.strftime('%Y%m%d'),
                                                        'dtnow': datetime.datetime.now().strftime('%Y%m%dT%H%M%SZ'),
                                                        'type': t,
                                                        'index':index})
                else :
                    t = u'阳历'
                    d2 = datetime.datetime(year, int(d1[1]), int(d1[2])) 
                    d3 = d2 + datetime.timedelta(days=1)
                    index = index+1
                    self.response.out.write(icalTemplate1 % {'name': name, 
                                                        'dtstart': d2.strftime('%Y%m%d'),
                                                        'dtend': d3.strftime('%Y%m%d'),
                                                        'dtnow': datetime.datetime.now().strftime('%Y%m%dT%H%M%SZ'),
                                                        'type': t,
                                                        'index':index})
        logging.debug('create ical for user:' + email)
        self.response.out.write(icalTemplate2)


class MainPage(webapp.RequestHandler):    
   
    @login_required
    def get(self):
                
        credentials = oauth.Credentials.gql("WHERE user = :user", user=users.get_current_user())
        credential = credentials.get()
        
        if not credential:
            logging.debug('no credential')
            self.redirect('/authcode')
            return
        elif credential.expire_date < datetime.datetime.now():
            logging.debug('update credential')
            self.redirect('/oauthupdate')
            return
        else:
            param = urllib.urlencode({
                'email': users.get_current_user().email()
            })
            self.redirect('/ical/?'+param)
        
def main():
    logging.getLogger().setLevel(logging.DEBUG)
    application = webapp.WSGIApplication([
           ('/', MainPage),
           ('/authcode', oauth.OAuthCode),
           ('/oauthtoken', oauth.OAuthToken),
           ('/oauthupdate', oauth.OAuthUpdate),
           ('/ical/', ICALPage),
           ('/ical/*.*', ICALPage)
        ], 
        debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
